package models

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"gitee.com/tsingeye/FreeEhome/tools/sqlDB"

	"gitee.com/tsingeye/FreeEhome/service/ehome/udp"
	"gitee.com/tsingeye/FreeEhome/tools/logs"
	"gitee.com/tsingeye/FreeEhome/tools/redisDB"
)

type onStreamNoneReader struct {
	App           string `json:"app"`
	MediaServerID string `json:"mediaServerId"`
	Schema        string `json:"schema"`
	Session       string `json:"stream"` //实时直播启动生成的session
	VHost         string `json:"vhost"`
}

//关闭流通知
func OnStreamNoneReader(requestBody []byte) (replyData map[string]interface{}) {
	replyData = map[string]interface{}{
		"code":  0,
		"close": false,
	}

	var hookData onStreamNoneReader
	if err := json.Unmarshal(requestBody, &hookData); err != nil {
		logs.BeeLogger.Error("HookController.OnStreamNoneReader() ---> requestBody=%s, json.Unmarshal() error:%s", requestBody, err)
		return
	}

	if hookData.App == "live" || hookData.App == "ehrecord" {
		//通过chnID取stream session
		//deviceID, err := redisDB.GetString(hookData.Session)
		//	chnID := hookData.Session
		//	fmt.Println("chnID = " + chnID)

		//streamSession, err := redisDB.GetString(chnID)
		deviceID, err := redisDB.GetString(hookData.Session)

		fmt.Printf("session = " + hookData.Session + "devid = " + deviceID)

		if err != nil {
			logs.BeeLogger.Error("HookController.OnStreamNoneReader() ---> requestBody=%s, redisDB.GetString() error:%s", requestBody, err)
			return
		}

		//redisDB.Del(chnID)

		//deviceID := strings.Split(chnID, "_")
		//go udp.ByeStream(deviceID[0], streamSession)

		redisDB.Del(hookData.Session)
		go udp.ByeStream(deviceID, hookData.Session)
	}

	return
}

type onPublish struct {
	App           string `json:"app"`
	ID            string `json:"id"`
	IP            string `json:"ip"`
	MediaServerID string `json:"mediaServerId"`
	Params        string `json:"params"`
	Port          int64  `json:"port"`
	Schema        string `json:"schema"`
	Session       string `json:"stream"`
	VHost         string `json:"vhost"`
}

//onPublish通知
func OnPublish(requestBody []byte) (replyData map[string]interface{}) {
	replyData = map[string]interface{}{
		"code":       0,
		"enableHls":  true,
		"enableRtxp": true,
		"msg":        "success",
	}

	var hookData onPublish
	if err := json.Unmarshal(requestBody, &hookData); err != nil {
		logs.BeeLogger.Error("HookController.OnPublish() ---> requestBody=%s, json.Unmarshal() error:%s", requestBody, err)
		return
	}

	switch hookData.App {
	case "live":
		//实时直播返回session
		replyData["enableMP4"] = false

		if hookData.Session != "" {
			redisDB.SetEX(hookData.Session, hookData.Session, 7*24*3600)
		}
	case "ehrecord":
		//实时直播返回session
		replyData["enableMP4"] = false

		if hookData.Session != "" {
			redisDB.SetEX(hookData.Session, hookData.Session, 7*24*3600)
			redisDB.SetEX("ehrecord", hookData.Session, 3)
		}
	default:
		//默认录像回放触发
		replyData["enableMP4"] = true
	}

	return
}

type onRecordMP4 struct {
	App string `json:"app"`
	URL string `json:"url"`
}

//onRecordMP4通知
func OnRecordMP4(requestBody []byte) (replyData map[string]interface{}) {
	var hookData onRecordMP4
	if err := json.Unmarshal(requestBody, &hookData); err != nil {
		logs.BeeLogger.Error("HookController.OnRecordMP4() ---> requestBody=%s, json.Unmarshal() error:%s", requestBody, err)
		return
	}

	if hookData.App == "ehrecord" {
		redisDB.SetEX("ehrecord", hookData.URL, 3)
	}

	return
}

//播放通知
func OnPlay(requestBody []byte) (replyData map[string]interface{}) {
	replyData = map[string]interface{}{
		"code": 0,
		"msg":  "success",
	}

	//判断当前流url是否存在，如果不存在，则调用点播指令；如果存在则直接返回

	return
}

type onStreamNotFound struct {
	MediaServerID string `json:"mediaServerId"`
	App           string `json:"app"`
	ID            string `json:"id"`
	IP            string `json:"ip"`
	Params        string `json:"params"`
	Port          int64  `json:"port"`
	Schema        string `json:"schema"`
	Stream        string `json:"stream"`
	VHost         string `json:"vhost"`
}

/*
{
   "mediaServerId" : "your_server_id",
   "app" : "live",
   "id" : "140183261486112",
   "ip" : "10.0.17.132",
   "params" : "",
   "port" : 49614,
   "schema" : "rtsp",
   "stream" : "obs",
   "vhost" : "__defaultVhost__"
}
*/
//未找到流
func OnStreamNotFound(requestBody []byte) (replyData map[string]interface{}) {
	// replyData = map[string]interface{}{
	// 	"code": 0,
	// 	"msg":  "success",
	// }

	// var hookData onStreamNotFound
	// if err := json.Unmarshal(requestBody, &hookData); err != nil {
	// 	logs.BeeLogger.Error("HookController.OnStreamNotFound() ---> requestBody=%s, json.Unmarshal() error:%s", requestBody, err)
	// 	return
	// }
	// //如有业务需要，则拿着app 和stream进行点播即可
	// return InviteReal(hookData.Stream, "MAIN")
	return
}

func InviteReal(channelID string, channelType string) (replyData map[string]interface{}) {
	strList := strings.Split(channelID, "_")
	if len(strList) != 2 {
		logs.BeeLogger.Warn("InviteReal() ---> channelID=%s, channelID format error!!!", channelID)
		return
	}

	realChannelID, err := strconv.ParseInt(strList[1], 0, 64)
	if err != nil {
		logs.BeeLogger.Warn("InviteStream() ---> channelID=%s, channelID format error!!!", channelID)
		return
	}

	var channelData sqlDB.ChannelTable
	if err := sqlDB.First(&channelData, "channelID = ?", channelID); err != nil {
		logs.BeeLogger.Error("InviteStream() ---> channelID=%s, sqlDB.First(&sqlDB.ChannelTable{}) error:%s", channelID, err)
		return
	}

	switch channelType {
	case "MAIN", "SUB", "THIRD":
	default:
		//默认使用子码流
		channelType = "SUB"
	}

	var ret map[string]interface{}
	ret = udp.InviteStream(channelData.DeviceID, realChannelID, channelType)
	errCode := ret["errCode"].(int)
	if errCode == 200 {
		fmt.Println("req sucess")
	}
	// client := &http.Client{
	// 	Transport: &http.Transport{
	// 		Dial: func(network, addr string) (net.Conn, error) {
	// 			conn, err := net.DialTimeout(network, addr, time.Second*time.Duration(config.EHomeAlarmForwardTimeout)) //设置建立连接超时
	// 			if err != nil {
	// 				return nil, err
	// 			}
	// 			conn.SetDeadline(time.Now().Add(time.Second * time.Duration(config.EHomeAlarmForwardTimeout))) //设置发送接受数据超时
	// 			return conn, nil
	// 		},
	// 		ResponseHeaderTimeout: time.Second * time.Duration(config.EHomeAlarmForwardTimeout),
	// 	},
	// }
	return
}
